<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport" />
    <title>上传图片</title>
    <style>
        input[type="file"] {
            display: none;
        }
        img {
            width: 30%;
            margin: 10px 0 10px 2.2%;
            border: 1px solid #ccc;
            vertical-align: top;
        }
        #imgDiv {
            background-color: #EEEEEE;
            text-align: left;
            min-height: 111px;
        }
        #uploadDiv {
            text-align: right;
        }
        .file {
            border: 1px solid #39C468;
            color: #39C468;
            height: 35px;
            padding: 0 10px;
            width: 80px;
            border-radius: 5px;
            background-color: white;
            font-size: 90%;
            margin-top: 10px;
        }
        #editerBtn {
            width: 80%;
            background-color: #39C468;
            color: white;
            height: 40px;
            display: block;
            margin: auto;
            margin-top: 40px;
            margin-bottom: 40px;
            border: none;
            border-radius: 5px;
        }

    </style>
</head>
<body>
<main>
    <div id="sendQuestion">
        <form id="addFeedbackForm">
            <div id="photos">
                <!--我这里限制的是5张图，所以加了5个file-->
                <input type="file" data-file="" class="noImgUrl" onchange="showPic(this)">
                <input type="file" data-file="" class="noImgUrl" onchange="showPic(this)">
                <input type="file" data-file="" class="noImgUrl" onchange="showPic(this)">
                <input type="file" data-file="" class="noImgUrl" onchange="showPic(this)">
                <input type="file" data-file="" class="noImgUrl" onchange="showPic(this)">
                <div id="imgDiv">
                </div>
                <div id="uploadDiv">
                    <input type="button" class="file" value="添加图片"/>
                </div>
            </div>
            <input type="button" value="提交" id="editerBtn">
        </form>
    </div>
</main>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
<script>
    $(".file").click(function(){
        var imgLength = document.getElementById('imgDiv').children.length;
        /*判断图片大于5张*/
        if(imgLength >= 5){
            alert('最多上传5张图');
            return false;
        }
        /*每次点击相当于添加图片相当于点击了.noImgUrl的第一个file*/
        document.getElementsByClassName('noImgUrl')[0].click();
    });
    //提交反馈
    $("#editerBtn").click(function () {
        uploadFile();
    });
    // 上传图片
    function uploadFile() {
        var xhr = new XMLHttpRequest();
        /*FormData，我们就可以轻松地使用Ajax方式进行文件上传了,参数自动获取form里name的值*/
        var fd = new FormData(document.getElementById('addFeedbackForm'));

        /* 事件监听 */
        xhr.upload.addEventListener("progress", uploadProgress, false);
        xhr.addEventListener("load", uploadComplete, false);
        xhr.addEventListener("error", uploadFailed, false);
        xhr.addEventListener("abort", uploadCanceled, false);
        /* 上传服务器端的URL ，参数自动获取form里name的值*/
        xhr.open("POST", "http://localhost:8080/mob/up/upload");
        xhr.send(fd);
    }

    function uploadProgress(evt) {

    }

    function uploadComplete(evt) {
        /* 当服务器发送响应时，会引发此事件 */
        $("#editerBtn").removeAttr('disabled');
        console.info(JSON.parse(evt.target.responseText).httpCode);
        if(JSON.parse(evt.target.responseText).httpCode == 200){
            alert('上传成功');
        }else {
            alert('上传失败');
        }
    }

    function uploadFailed(evt) {
        alert('上传文件时出错');
    }

    function uploadCanceled(evt) {
        alert('上传被取消');
    }
    function showPic(obj) {
        var fullPath = getFullPath(obj);
        if (fullPath) {
            document.getElementById("pic").src = fullPath + "";
        }
    };
    //选择图片
    function getFullPath(obj) {
        //一次选择一张
        if (obj) {
            //Internet Explorer
            if (window.navigator.userAgent.indexOf("MSIE") >= 1) {
                obj.select();
                return document.selection.createRange().text;
            }

            //兼容chrome、火狐等，HTML5获取路径
            if (typeof FileReader != "undefined") {
                var reader = new FileReader();
                try {
                    reader.onload = function (e) {
                        var fileData = obj.files[0];
                        /*这里读到的是图片大小，也可以在这里加入图片大小限制*/
                        var size = (fileData.size/1024).toFixed(1);
                        var type = fileData.type;
                        /*图片类型限制*/
                        if (type == 'image/png' ||type == 'image/jpeg' ||type == 'image/bmp' ||type == 'image/gif'){

                            console.info('图片大小：'+size+'KB','类型：'+type);
                            document.getElementById('imgDiv').innerHTML += '<img name="'+obj.files[0].name+'" type="image" class="uploadImg" onclick="deleteImg(this)" src="' + e.target.result + '"/>';
                            $(".uploadImg").height($(".uploadImg").width());
                            $(obj).attr({'name':'imageFileName','data-file':obj.files[0].name});
                            $(obj).removeClass('noImgUrl');

                        }else {
                            alert('只允许上传jpg、png、gif、bmp格式的图片');
                            return false;
                        }
                    };
                    reader.readAsDataURL(obj.files[0]);
                } catch (err) {
                    console.info(err.message);
                }
            } else if (browserVersion.indexOf("SAFARI") > -1) {
                alert("暂时不支持Safari浏览器!");
            }else {
                alert("浏览器暂时不支持!");
            }

        }
    };
    //删除图片
    function deleteImg(obj) {
        var check = confirm('是否确定删除');
        if (check){
            //查找删除img对应的input
            for (var x = 0;x < $("input[type='file']").length;x++){
                if($("input[type='file']").eq(x).attr('data-file') == $(obj).attr('name')){
                    console.info($("input[type='file']").eq(x).attr('data-file'),$(obj).attr('name'),x);
                    $("input[type='file']").eq(x).addClass('noImgUrl');
                    $("input[type='file']").eq(x).removeAttr('name');
                    $("input[type='file']").eq(x).removeAttr('data-file');
                    $(obj).remove();
                    return false;
                }
            }
        }
    }
</script>
</body>
</html>

